package com.lb.shopguide.ui.fragment.guide;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.blankj.utilcode.util.LogUtils;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseFragment;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.config.UserConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.GuideAdBean;
import com.lb.shopguide.entity.recommend.RecBannerBean;
import com.lb.shopguide.event.guide.BackToHomeEvent;
import com.lb.shopguide.event.guide.QuickPayEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.event.jump.JumpMemberEvent;
import com.lb.shopguide.event.jump.JumpMemberListEvent;
import com.lb.shopguide.event.jump.JumpRecEvent;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.dialog.DialogGotoRecModule;
import com.lb.shopguide.ui.fragment.guide.member.FragmentMember;
import com.lb.shopguide.ui.fragment.guide.order.FragmentSureOrder;
import com.lb.shopguide.ui.fragment.guide.recommend.FragmentRecommendHome;
import com.lb.shopguide.ui.fragment.guide.recommend.FragmentVirtualActivity;
import com.lb.shopguide.ui.view.LbBottomBar;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.AdJumpUtil;
import com.lb.shopguide.util.lb.BizUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by kang on 2017/5/31.
 */

public class FragmentMain extends SupportFragment {

    private View view;
    private LbBottomBar lbBottomBar;

    private BaseMainFragment[] mFragments = new BaseMainFragment[4];
    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FORTH = 3;

    private GuideAdBean guideAdBean;
    private GuideAdBean jumpBean;
    private DialogGotoRecModule dialogGotoRecModule;
    private boolean quickPayFlag = false;
    private boolean jumpFlag = false;

    public static FragmentMain newInstance() {
        return new FragmentMain();
    }

    public static FragmentMain newInstance(GuideAdBean guideAdBean) {
        FragmentMain fragmentMain = new FragmentMain();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.GUIDEAD_BEAN, guideAdBean);
        fragmentMain.setArguments(bundle);
        return fragmentMain;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_guide_main, container, false);
        initData();
        initView();
        return view;
    }

    private void initData() {
        EventBus.getDefault().register(this);
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.GUIDEAD_BEAN)) {
            guideAdBean = (GuideAdBean) bundle.getSerializable(AppConstant.GUIDEAD_BEAN);
        }
    }

    private void initView() {
        SupportFragment firstFragment = findChildFragment(FragmentHome.class);
        if (firstFragment == null) {
            mFragments[FIRST] = FragmentHome.newInstance();
            mFragments[SECOND] = FragmentMember.newInstance();
            mFragments[THIRD] = FragmentRecommendHome.newInstance();
            mFragments[FORTH] = FragmentGuideMine.newInstance();

            loadMultipleRootFragment(R.id.fl_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND],
                    mFragments[THIRD],
                    mFragments[FORTH]);
        } else {
            // 这里我们需要拿到mFragments的引用,也可以通过getChildFragmentManager.getFragments()自行进行判断查找(效率更高些),用下面的方法查找更方便些
            mFragments[FIRST] = findChildFragment(FragmentHome.class);
            mFragments[SECOND] = findChildFragment(FragmentMember.class);
            mFragments[THIRD] = findChildFragment(FragmentRecommendHome.class);
            mFragments[FORTH] = findChildFragment(FragmentGuideMine.class);
        }

        lbBottomBar = view.findViewById(R.id.bottom_bar);
        lbBottomBar.setOnTabSelectedListener(new LbBottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int pos, int prePos) {
                showHideFragment(mFragments[pos], mFragments[prePos]);
            }
        });
    }


    /**
     * 启动同级fragment
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void startBrother(StartBrotherEvent event) {
        start(event.targetFragment);
    }

    @Subscribe
    public void backToHome(BackToHomeEvent event) {
        lbBottomBar.performClick(LbBottomBar.BOTTOM_HOME);
    }

    @Subscribe(sticky = true)
    public void jumpToMessage(JumpMemberEvent event) {
        if (getTopFragment() instanceof FragmentMain) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    lbBottomBar.performClick(LbBottomBar.BOTTOM_MESSAGE);
                    EventBus.getDefault().postSticky(new JumpMemberListEvent());
                }
            }, 500);
        }
    }

    @Subscribe(sticky = true)
    public void excuteRec(JumpRecEvent event) {
        if (getTopFragment() instanceof FragmentMain) {
            jumpBean = JsonUtil.getGson().fromJson(event.getContent(), GuideAdBean.class);
            if (jumpBean.getJumpMode() == RecBannerBean.JUMP_ACTIVITY) {
                jumpBean.setJumpUrl(BizUtil.fixActivityUrl(jumpBean.getJumpUrl(), "XD0010"));
            }
            SupportFragment firstFragment = findChildFragment(FragmentHome.class);
            if (firstFragment == null) {
                jumpFlag = true;
            } else {
                jumpLogic(jumpBean);
            }
        }
    }

    @Subscribe(sticky = true)
    public void quickPay(QuickPayEvent event) {
        quickPayFlag = true;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (quickPayFlag) {
            start(FragmentSureOrder.newInstance());
            quickPayFlag = false;
        }
        if (jumpFlag) {
            jumpLogic(jumpBean);
            jumpFlag = false;
        }
    }

    private void jumpLogic(GuideAdBean bean) {
        BaseFragment fragment = AdJumpUtil.jumpToDestination(bean.getJumpMode(), bean.getPageSdCode(), bean.getRelCode(), bean.getRelName(), bean.getJumpUrl());
        if (fragment instanceof FragmentRecommendHome) {
            lbBottomBar.performClick(LbBottomBar.BOTTOM_REC);
        } else if (fragment instanceof FragmentVirtualActivity) {
            Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString(AppConstant.WEB_URL, fragment.getArguments().getString(AppConstant.WEB_URL));
            bundle.putString(AppConstant.WEB_TITLE, fragment.getArguments().getString(AppConstant.WEB_TITLE));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            start(fragment);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (guideAdBean != null) {
            LogUtils.dTag("FragmentMain", "jumpLogic");
            jumpLogic(guideAdBean);
            guideAdBean = null;
            return;
        }
        UserConfigManager config = UserConfigManager.getInstance(getContext());
        if (!config.isRecOpen() && dialogGotoRecModule == null) {
            if (!config.isFirstPooDialogGuide()) {
                dialogGotoRecModule = DialogGotoRecModule.getDialogGotoRecModule(DialogGotoRecModule.DIALOG_FIRST);
                dialogGotoRecModule.show(getFragmentManager(), FragmentMain.class.getCanonicalName());
                dialogGotoRecModule.setOnDialogClickListener(new DialogGotoRecModule.OnDialogClickListener() {
                    @Override
                    public void gotoRec() {
                        dialogGotoRecModule.dismissAllowingStateLoss();
                        lbBottomBar.performClick(LbBottomBar.BOTTOM_REC);
                    }

                    @Override
                    public void dialogDismiss() {
                        config.setFirstPooDialogGuide(true);
                        config.save2Sp(true);
                    }
                });
            } else {
                if (!config.isSecondPooDialogGuide()) {
                    dialogGotoRecModule = DialogGotoRecModule.getDialogGotoRecModule(DialogGotoRecModule.DIALOG_SECOND);
                    dialogGotoRecModule.show(getFragmentManager(), FragmentMain.class.getCanonicalName());
                    dialogGotoRecModule.setOnDialogClickListener(new DialogGotoRecModule.OnDialogClickListener() {
                        @Override
                        public void gotoRec() {
                            dialogGotoRecModule.dismissAllowingStateLoss();
                            lbBottomBar.performClick(LbBottomBar.BOTTOM_REC);
                        }

                        @Override
                        public void dialogDismiss() {
                            config.setSecondPooDialogGuide(true);
                            config.save2Sp(true);
                        }
                    });
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
